package com.gxa.mobile.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.core.result.MessageCode;
import com.gxa.core.result.Result;
import com.gxa.mobile.exception.CustomException;
import com.gxa.mobile.utils.HttpClientUtil;
import com.gxa.mobile.utils.JsonUtils;
import com.gxa.mobile.utils.UserThreadLocal;
import com.gxa.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lch
 * @Date 2024/3/26 16:27
 * @Description 拦截器，验证token
 **/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入登录拦截");

        //放行探测请求
        String method = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)) {
            return true;
        }

        //从请求头获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            //从参数中再获取一次token
            token = request.getParameter("token");
            if (token == null || token.isEmpty()) {
                //没有登录，抛出异常(未携带token)
                throw new CustomException(MessageCode.NO_LOGIN);
            }
        }

        //从认证中心中获取用户信息
        Map<String,String> map=new HashMap<>();
        map.put("token",token);
        String jsonResult= HttpClientUtil.doPost("http://localhost:8083/user/findUserByToken",map);

        //将返回的json转换成result
        Result result = JsonUtils.jsonToPojo(jsonResult, Result.class);

        //获取用户信息
        ObjectMapper objectMapper = new ObjectMapper();
        User user= objectMapper.convertValue(result.getData(), User.class);

        if (user==null){
            //非法token
            throw new CustomException(MessageCode.TOKEN_ERROR);
        }
        log.info("用户信息:{}",user);

        //把用户信息保存到本地缓存
        UserThreadLocal.setUser(user);
        return true;
    }
}
